﻿#region License

// // -------------------------------------------------------------------------------------
// // This information refers to ExceptionCountAspect.cs
// // 
// // Copyright 2012 ELEN7046 Group 2
// // 
// // Last Modified on: 2012-06-10
// // 
// // Contributors:
// // 
// // Amith Sewnarain
// // Elmar Vosloo
// // Jason Thorne
// // Satish Jewan
// // 
// // Wits University 
// // School of Electrical & Information Engineering
// // Software Engineering Tools and Techniques
// // 
// // -------------------------------------------------------------------------------------
// // 
// // This file (ExceptionCountAspect.cs) is part of the DishDash Event Visualization System.
// // 
// // DishDash is free software: you can redistribute it and/or modify
// // it under the terms of the GNU General Public License as published by
// // the Free Software Foundation, either version 3 of the License, or
// // (at your option) any later version.
// // 
// // DishDash is distributed in the hope that it will be useful,
// // but WITHOUT ANY WARRANTY; without even the implied warranty of
// // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// // GNU General Public License for more details.
// // 
// // You should have received a copy of the GNU General Public License
// // along with DishDash.  
// // If not, see <http://www.gnu.org/licenses/>.
// // -------------------------------------------------------------------------------------

#endregion

#region Using Directives

using System;
using System.Linq;
using System.Reflection;
using InstrumentationLibrary;
using InstrumentationWrapper;
using Mono.Cecil;
using Mono.Cecil.Cil;

#endregion

namespace InstrumentAspect
{
    public class ExceptionCountAspect : IInstrumentationAspect
    {
        private readonly InstrumentationAttribute _identifyingAttribute = new ExceptionCountAttribute();

        #region IInstrumentationAspect Members

        public InstrumentationAttribute IdentifyingAttribute
        {
            get { return this._identifyingAttribute; }
        }

        public void Instrument(MethodDefinition method)
        {
            MethodInfo aspectMethod = typeof (InstrumentationWrapperService).GetMethod("LogCount",
                                                                                       new Type[] {typeof (string)});

            MethodReference aspectMethodReference = null;
            aspectMethodReference = method.Module.Import(aspectMethod);

            var systemAssembly = Mono.Cecil.AssemblyDefinition.ReadAssembly(typeof (Console).Assembly.Location);
            var exceptionType = (from s in systemAssembly.Modules[0].Types
                                 where s.Name == "Exception"
                                 select s).Single();

            var internalExTypeRef = method.Module.Import(exceptionType);


            //Inserting instruction where try block will finish.
            method.Body.Instructions.Insert(
                method.Body.Instructions.Count - 1,
                Instruction.Create(OpCodes.Leave_S,
                                   method.Body.Instructions[method.Body.Instructions.Count - 1]));

            //Add NOP instruction on line before RETURN
            method.Body.Instructions.Insert(
                method.Body.Instructions.Count - 1,
                Instruction.Create(OpCodes.Nop));

            // ------------------------------------------------------------------
            // Instrumentation bits.
            // ------------------------------------------------------------------
            // Add the parameter instruction first
            method.Body.Instructions.Insert(
                method.Body.Instructions.Count - 1,
                Instruction.Create(OpCodes.Ldstr,
                                   (method.DeclaringType.FullName + "." + method.Name + ".exceptionCount").ToLower()));

            // Add the call the to the method
            method.Body.Instructions.Insert(
                method.Body.Instructions.Count - 1,
                Instruction.Create(OpCodes.Call,
                                   aspectMethodReference));

            // ------------------------------------------------------------------

            // Add rethrow on line before 
            method.Body.Instructions.Insert(
                method.Body.Instructions.Count - 1,
                Instruction.Create(OpCodes.Rethrow));

            // Add NOP instruction on line before RETURN
            method.Body.Instructions.Insert(
                method.Body.Instructions.Count - 1,
                Instruction.Create(OpCodes.Nop));

            var exceptionHandler = new ExceptionHandler(ExceptionHandlerType.Catch);

            exceptionHandler.CatchType = internalExTypeRef;

            // Start try on beginning of method body
            exceptionHandler.TryStart = method.Body.Instructions[0];

            // End try on inserted leave_S
            exceptionHandler.TryEnd = method.Body.Instructions[method.Body.Instructions.Count - 7];

            // Start handler just before instrumentation logging instruction
            exceptionHandler.HandlerStart = method.Body.Instructions[method.Body.Instructions.Count - 5];

            // End handler prior to return
            exceptionHandler.HandlerEnd = method.Body.Instructions[method.Body.Instructions.Count - 1];

            method.Body.ExceptionHandlers.Add(exceptionHandler);
        }

        #endregion
    }
}